<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use Doctrine\Common\Util\Debug;

class Agen extends Controller{

	private $sidebar_menu_links = array(
		'detail' => 'Detail',
		'daftar_customer' => 'Daftar Customer',
		'daftar_speedy' => 'Daftar Speedy',
	);

	private $pagination_config = array(
		'per_page' => 10,
		'num_links' => 10,
		'full_tag_open' => "<div id='pagination'>",
		'full_tag_close' => "</div>",
	);
	
	function __construct(){
		parent::Controller();
		$this->current_user = models\Current_user::get_user();
		$this->kategori_user = models\Current_user::get_kategori();
		if(!$this->current_user || $this->kategori_user != 'Administrator')
			show_error(array('Halaman ini tidak bisa diakses oleh anda!',anchor('','Kembali ke halaman utama')),403);
	}
	
	function index(){
		
		$this->load->library('pagination');

		$this->pagination_config['base_url'] = base_url().'/'.$this->uri->segment(1).'/index';
		$this->pagination_config['total_rows'] = $this->doctrine->em
			->createQuery('SELECT COUNT(a.id) FROM models\Agen a')
			->getSingleScalarResult();

		$this->pagination->initialize($this->pagination_config);

		if(!$this->uri->segment(3)) $offset = 0;
		else $offset = $this->uri->segment(3);
		
		$agen = $this->doctrine->em
			->createQuery('SELECT a FROM models\Agen a ORDER BY a.username ASC')
			->setMaxResults($this->pagination_config['per_page'])
			->setFirstResult($offset)
			->getResult();

		foreach($agen as $a){

			$block = new Block();

			$block->add_grid()
				->add_info($a->get_username())
				->add_nama_info($a,'images/orang.png');

			$block->add_grid()
				->add_info(
					$a->get_alamat().br().
					$a->get_kota().' '.
					$a->get_kodepos().br().
					$a->get_propinsi(),
					'images/rumah.png'
				);

			$block->add_grid()
				->add_info($a->get_telepon(),'images/telepon.png')
				->add_info(mailto($a->get_email()),'images/edit.png');

			$block->set_class('daftar_akun');

			$this->main_content->add_block($block);
		}

		$this->main_content->add_pagination();

		$this->headbar->add_header();
		$this->headbar->add_menu('register','Daftar Agen Baru',$this->uri->segment(1).'/register');
		$this->sidebar->create_custom('p','Daftar seluruh agen Smart Connect Internet Home Services');
		
        $this->load->view('template', array('title' => 'Agen'));
	}
	
	function detail($username = null){
		
		if(!$username) show_404();

		$agen = $this->doctrine->em->getRepository('models\Agen')
			->findOneBy(array('username' => $username));
		if(!$agen) show_404();
		
		$this->main_content->add_custom('p','Detail agen '.$agen->get_nama());

		$this->main_content->add_block('Akun')
			->add_hidden_field('id',$agen->get_id())
			->add_editable_username($agen)
			->add_editable_data('nama','Nama',$agen->get_nama());

		$this->main_content->add_block('Alamat')
			->add_editable_data('alamat','Alamat',$agen->get_alamat())
			->add_editable_data('kota','Kota',$agen->get_kota())
			->add_editable_data('kodepos','Kode Pos',$agen->get_kodepos())
			->add_editable_propinsi($agen->get_propinsi());

		$this->main_content->add_block('Kontak')
			->add_editable_data('telepon','No Telepon',$agen->get_telepon())
			->add_editable_email($agen->get_email());

		$this->main_content->set_editable();
		$this->main_content->set_deletable();

		$this->headbar->add_header();
		$this->sidebar
			->create_identitas($agen)
			->create_menu($this->sidebar_menu_links);

        $this->load->view('template',array('title' => 'Detail Agen'));
    }
	
	function ajax_edit($username = null){
		if(IS_AJAX){

			$this->load->library('form_validation');

			if($this->form_validation->run('agen_update') == TRUE){

				$agen = $this->doctrine->em->getRepository('models\Agen')->findOneBy(array('username' => $username));
				if(!$agen) {
					$returned_data = array('status' => 'gagal');
					echo json_encode($returned_data);
					return false;
				}

				$username = $this->generator->generate_username('models\Agen',$this->input->post('username'));

				$agen->set_username($username);
				$agen->set_nama($this->input->post('nama'));
				$agen->set_alamat($this->input->post('alamat'));
				$agen->set_kota($this->input->post('kota'));
				$agen->set_kodepos($this->input->post('kodepos'));
				$agen->set_propinsi($this->input->post('propinsi'));
				$agen->set_telepon($this->input->post('telepon'));
				$agen->set_email($this->input->post('email'));

				$this->doctrine->em->flush();

				$returned_data = array(
					'status' => 'sukses',
					'username' => $username,
				);

			} else {
				$returned_data = array(
					'status' => 'gagal',
					'error' => validation_errors(),
				);
			}

			echo json_encode($returned_data);

		} else show_404();
	}

	function ajax_hapus(){
		
		if(IS_AJAX){
		
			$username = $this->input->post('username');

			$agen = $this->doctrine->em->getRepository('models\Agen')->findOneBy(array('username' => $username));
			$this->doctrine->em->remove($agen);
			$this->doctrine->em->flush();

			$this->session->set_flashdata('status', 'Berhasil menghapus teknisi '.$username);

		} else show_404();
    }
	
	function daftar_customer($username=null){

		if(!$username) show_404();

		$agen = $this->doctrine->em->getRepository('models\Agen')
			->findOneBy(array('username' => $username));
		if(!$agen) show_404();

		$customer = $agen->get_customer();
		$total_rows = count($customer);

		if($total_rows != 0){

			$this->main_content->add_custom('p','Daftar Customer yang ditangani agen '.$agen->get_nama());

        	$this->load->library('pagination');

			$this->pagination_config['base_url'] = base_url().'/'.$this->uri->segment(1).'/'.$this->uri->segment(2).'/'.$this->uri->segment(3);
			$this->pagination_config['uri_segment'] = 4;
			$this->pagination_config['total_rows'] = $total_rows;

			$this->pagination->initialize($this->pagination_config);

			if(!$this->uri->segment(4)) $offset = 0;
			else $offset = $this->uri->segment(4);

			$endloop = $offset + $this->pagination_config['per_page'];
			if($total_rows <= $endloop) $endloop = $total_rows;

			for($i = $offset; $i < $endloop; $i++){

				$c = $customer[$i];

				// avatar perusahaan dengan pribadi berbeda
				if(get_class($c) == "models\Perusahaan") 
					$avatar = 'images/pabrik.png';
				else $avatar = 'images/orang.png';

				$block = new Block();

				$block->add_grid()
					->add_info($c->get_username())
					->add_nama_info($c,$avatar)
					->add_info('Paket: '.$c->get_paket_langganan()->get_nama());

				$block->add_grid()
					->add_info(
						$c->get_alamat().br().
						$c->get_kota().' '.
						$c->get_kodepos().br().
						$c->get_propinsi(),
						'images/rumah.png'
					);

				$block->add_grid()
					->add_info($c->get_telepon(),'images/telepon.png')
					->add_info($c->get_telepon_seluler(),'images/hape.png')
					->add_info($c->get_fax(),'images/fax.png')
					->add_info(mailto($c->get_email()),'images/edit.png');
				
				$block->set_class('daftar_akun');
				$this->main_content->add_block($block);
			}
			$this->main_content->add_pagination();
		} else {
			$this->main_content->add_custom('p','Tidak ada Customer yang ditangani agen '.$agen->get_nama());
		}

		$this->headbar->add_header();
		$this->sidebar->create_identitas($agen);
		$this->sidebar->create_menu($this->sidebar_menu_links);

        $this->load->view('template', array('title' => 'Customer yang ditangani'));

	}

	function daftar_speedy($username=null){

		if(!$username) show_404();

		$agen = $this->doctrine->em->getRepository('models\Agen')
			->findOneBy(array('username' => $username));
		if(!$agen) show_404();

		$speedy = $agen->get_speedy();
		$total_rows = count($speedy);

		if($total_rows != 0){

			$this->main_content->add_custom('p','Daftar langganan Speedy yang ditangani agen '.$agen->get_nama());

        	$this->load->library('pagination');

			$this->pagination_config['base_url'] = base_url().'/'.$this->uri->segment(1).'/'.$this->uri->segment(2).'/'.$this->uri->segment(3);
			$this->pagination_config['uri_segment'] = 4;
			$this->pagination_config['total_rows'] = $total_rows;

			$this->pagination->initialize($this->pagination_config);

			if(!$this->uri->segment(4)) $offset = 0;
			else $offset = $this->uri->segment(4);

			$endloop = $offset+$this->pagination_config['per_page'];
			if($total_rows <= $endloop) $endloop = $total_rows;

			for($i = $offset; $i < $endloop; $i++){

				$s = $speedy[$i];

				$block = new Block();

				$block->add_grid()
					->add_nama_info($s,'images/orang.png')
					->add_info('Paket: '.$s->get_paket_speedy());

				$block->add_grid()
					->add_info($s->get_alamat(),'images/rumah.png');

				$block->add_grid()
					->add_info($s->get_telepon(),'images/telepon.png');
				
				$block->set_class('daftar_akun');
				$this->main_content->add_block($block);

			}
			$this->main_content->add_pagination();

		} else {
			$this->main_content->add_custom('p','Tidak ada langganan Speedy yang ditangani agen '.$agen->get_nama());
		}

		$this->headbar->add_header();
		$this->sidebar->create_identitas($agen);
		$this->sidebar->create_menu($this->sidebar_menu_links);

        $this->load->view('template', array('title' => 'Daftar Speedy yang ditangani agen'));

	}
	
	function register(){
	
		$this->config->load('dropdown_options');
		$option_propinsi = $this->config->item('propinsi');

		$this->main_content->add_block('Akun')
			->add_username_field('models\Agen')
			->add_text_field('nama','Nama');

		$this->main_content->add_block('Alamat')
			->add_text_field('alamat','Alamat')
			->add_text_field('kota','Kota')
			->add_text_field('kodepos','Kode Pos')
			->add_dropdown_field('propinsi','Propinsi',$option_propinsi); 

		$this->main_content->add_block('Kontak')
			->add_text_field('telepon','Telepon')
			->add_text_field('email','Email');

		$this->main_content->set_form_register();

		$this->headbar->add_header();

		$this->sidebar->create_custom('p','Username dan password akan otomatis dikirim ke alamat email yang diinputkan');

		$this->load->view('template', array('title' => 'Register Agen'));
    }

	function ajax_register(){
		if(IS_AJAX){

			$this->load->library('form_validation');

			if($this->form_validation->run('agen') == TRUE){

				$agen = new models\Agen();

				//generate username & password
				$this->load->library('generator');
				if($this->input->post('tipe_username') == 'manual')
					$username = $this->generator->generate_username('models\Agen',$this->input->post('username'));
				else $username = $this->generator->generate_username('models\Agen');
				$password = $this->generator->generate_password();

				$agen->set_username($username);
				$agen->set_password($password);

				//akun
				$agen->set_nama($this->input->post('nama'));

				//alamat
				$agen->set_alamat($this->input->post('alamat'));
				$agen->set_kodepos($this->input->post('kodepos'));
				$agen->set_kota($this->input->post('kota'));
				$agen->set_propinsi($this->input->post('propinsi'));

				//kontak
				$agen->set_telepon($this->input->post('telepon'));
				$agen->set_email($this->input->post('email'));

				//insert ke database
				$this->doctrine->em->persist($agen);
				$this->doctrine->em->flush();

				$this->load->library('email_gateway');
				$email = $this->input->post('email');
				$log_email = $this->email_gateway->send_new_akun_email($email, $username, $password);

				$returned_data = array(
					'status' => 'sukses',
				);

				$this->session->set_flashdata('status', 'Berhasil manambah agen '.$this->input->post('nama')."! <br /> Username dan password telah terkirim ke email agen");
			} else {

				$returned_data = array(
					'status' => 'gagal',
					'error' => validation_errors(),
				);
			}

			echo json_encode($returned_data);

		} else show_404(); 
	}
}
